package com.jy.rhin.domain.notification.participant;

import com.jy.rhin.domain.exception.RhinInfraErrorType;
import com.jy.rhin.domain.notification.participant.entity.ParticipantDO;
import com.jy.rhin.infra.uitl.Asserts;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author WeiQ
 * @date 2022/6/28 9:29
 * 参与者域服务
 */
@Service
public class ParticipantDomainService {

    @Resource
    private ParticipantDao participantDao;

    /**
     * 主键查询
     *
     * @param id
     * @return
     */
    public ParticipantDO queryById(Long id) {
        return participantDao.queryById(id);
    }

    /**
     * 保存参与者信息
     *
     * @param participant
     * @return
     */
    public Long saveParticipant(ParticipantDO participant) {
        ParticipantDO old;
        if (Objects.isNull(participant.getId())) {
            old = participantDao.queryByCode(participant.getParticipantCode());
            //标识code唯一
            Asserts.isNull(old, RhinInfraErrorType.PARTICIPANT_CODE_EXISTS);
        } else {
            old = participantDao.queryById(participant.getId());
            //主键查询失败
            Asserts.nonNull(old, RhinInfraErrorType.PARTICIPANT_NOT_FOUND);
            participant.maintainOriginalCreator(old.getCreateBy(), old.getCreateTime());
            //检验code、数据角色信息一致性
            boolean status = old.checkCodeAndRole(participant.getParticipantCode(), participant.getParticipantRole());
            Asserts.isTrue(status, RhinInfraErrorType.PARTICIPANT_CODE_ROLE_ERROR);
        }
        return participantDao.save(participant);
    }

    /**
     * 新增参与者信息
     * @param participant
     * @return
     */
    public Long addParticipant(ParticipantDO participant) {
        ParticipantDO participantDO = participantDao.queryByCode(participant.getParticipantCode());
        if(Objects.isNull(participantDO)){
           return participantDao.save(participant);
        }
        return participantDO.getId();
    }
}
